<template>
  <div id="appds">
    <div>
      <el-card style="width: 500px;height: 620px;background-color: rgba(255,255,255,0.3);margin: 3% auto;position: relative">
        <div style="position: absolute;right: 20px" class=""><i class="el-icon-close" style="font-size: 20px;cursor: pointer;" @click="toLogin"></i></div>
        <el-form :model="user" ref="ruleForm"  :rules="rules" label-width="10px" style="width: 400px;margin: 30px auto">
          <el-form-item prop="username">
            <el-input type="text" placeholder="账号" prefix-icon="el-icon-user" v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" placeholder="密码" prefix-icon="el-icon-lock" v-model="user.password"></el-input>
          </el-form-item>
          <el-form-item prop="trueName">
            <el-input type="text" placeholder="真实姓名" prefix-icon="el-icon-user" v-model="user.trueName"></el-input>
          </el-form-item>
          <el-form-item prop="phone">
            <el-input type="text" placeholder="电话" prefix-icon="el-icon-phone" v-model="user.phone"></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input type="text" placeholder="邮箱" prefix-icon="el-icon-s-platform" v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item prop="majorId">
            <template>
              <div style="text-align: left">
                <el-select v-model="user.majorId" :value="user.majorId" placeholder="请选择专业" @change="getClassArr">
                  <el-option v-for="item in majorArr" :label="item.majorName" :value="item.id" :key="item.id"></el-option>
                </el-select>
              </div>
            </template>
          </el-form-item>
          <el-form-item prop="classId">
            <template>
              <div style="text-align: left">
                <el-select v-model="user.classId" :value="user.classId" placeholder="请选择班级">
                  <el-option v-for="item in classArr" :label="item.className" :value="item.id" :key="item.id"></el-option>
                </el-select>
              </div>
            </template>
          </el-form-item>

          <el-form-item >
            <el-row :gutter="20">
              <el-col  :span="16">
                <el-input  prop="code" type="text" placeholder="验证码" prefix-icon="el-icon-circle-close" v-model="verification"></el-input>
              </el-col>
              <el-col :span="8">
                <el-button v-show="!showCode" @click="getCode">获取验证码</el-button>
                <img v-show="showCode" :src="codeImg" style="width: 110px;height: 32px;background: white" @click="getCode">
              </el-col>
            </el-row>

          </el-form-item>
          <el-form-item >
            <el-button type="warning" @click="reg('ruleForm')">注册</el-button>
            <el-button type="primary" @click="toLogin">返回</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<style>
#appds{
  background-image: url("/public/imgs/classroom1.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  text-align: center;
  overflow: hidden;
}
</style>
<script>
export default {
  data() {
    return {
      showCode:false,
      labelPosition: 'right',
      verification:"",
      user: {
        username: '',
        password: '',
        trueName:'',
        phone:'',
        email:'',
        majorId:'',
        classId:'',
        className:'',
        majorName:''
      },
      majorArr: [],
      classArr:[],
      codes:"",
      option:{
        canvasId:'mycanvas',
        width:200,
        height:50,
        txt:''
      },
      codeImg:'',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur' },
          {pattern:/^([1-9A-Za-z]*)$/,message:'请输入以字母和数字组成的密码',trigger: 'blur'}
        ],
        trueName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
        ],
        phone:[
          { required: true, message: '请输入电话', trigger: 'blur' },
          {pattern:/^1\d{10}$/,message:'请输入正确的电话',trigger: 'blur'}
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' },
            /*^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$*/
          {pattern:/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,message:'请输入邮箱',trigger: 'blur'}
        ],
        majorId:[
          { required: true, message: '专业不能为空', trigger: 'blur' }
        ],
        classId:[
          { required: true, message: '班级不能为空', trigger: 'blur' }
        ],
        code:[{ required: true, message: '验证码不能为空', trigger: 'blur' }]
      }
    };
  },
  methods: {
    /*从后端获取验证码*/
    getCode(){
      let url = "http://localhost:9281/code";
      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.codeImg = jsonResult.data;
          //this.code(this.options);
          this.showCode = true;
        } else {
          alert(jsonResult.message);
          //this.code(this.options);
        }
      })


    },

    /*产生随机数字*/
    randomNum(min,max){
      return Math.floor(Math.random()*(max-min)+min);
    },

    //生产验证码
    produceCode(options){
      this.codes="";
      var random=new Array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
          'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z');
      for(var i=0;i<4;i++){
        var index=Math.floor(Math.random()*60);
        this.codes+=random[index];
      }
      options.txt=this.codes;
    },
    randomColor(min,max){
      var r=this.randomNum(min,max);
      var g=this.randomNum(min,max);
      var b=this.randomNum(min,max);
      return "rgb("+r+","+g+","+b+")";
    },

    code(options){
      console.log(options)
      //this.produceCode(options);
      var canvas=document.getElementById(options.canvasId);
      canvas.width=options.width||300;//画布的宽
      canvas.height=options.height||150;//画布的高
      var ctx=canvas.getContext("2d");//创建一个canvas对象
      ctx.textBaseline="middle";
      ctx.fillStyle=this.randomColor(60,255);
      ctx.fillRect(0,0,canvas.width,canvas.height);
      for(var i=0;i<options.txt.length;i++){
        var txt=options.txt.charAt(i);
        ctx.font='50px SimHei';
        ctx.fillStyle = this.randomColor(60, 180); /*随机生成字体颜色*/
        ctx.shadowOffsetY = this.randomNum(-3, 3);
        ctx.shadowBlur = this.randomNum(-3, 3);
        ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
        var x = options.width / (options.txt.length+1) * (i+1);
        var y = options.height / 2;
        var deg = this.randomNum(-30, 30);
        /*设置旋转角度和坐标原点*/
        ctx.translate(x, y);
        ctx.rotate(deg * Math.PI / 180);
        ctx.fillText(txt, 0, 0);
        /*恢复旋转角度和坐标原点*/
        ctx.rotate(-deg * Math.PI / 180);
        ctx.translate(-x, -y);
      }
      for (let i = 0; i < this.randomNum(1,4); i++) {
        ctx.strokeStyle = this.randomColor(40, 180);
        ctx.beginPath();
        ctx.moveTo(this.randomNum(0, options.width), this.randomNum(0, options.height));
        ctx.lineTo(this.randomNum(0, options.width), this.randomNum(0, options.height));
        ctx.stroke();
      }
      for (let i = 0; i < options.width / 6; i++) {
        ctx.fillStyle = this.randomColor(0, 255);
        ctx.beginPath();
        ctx.arc(this.randomNum(0, options.width), this.randomNum(0, options.height), 1, 0, 2 * Math.PI);
        ctx.fill();
      }
    },
    toLogin(){
      this.$router.push("/");
    },
    reg(formName){
      this.$refs[formName].validate((valid) => {
        if(valid){
            for (let i = 0; i < this.majorArr.length; i++) {
              if(this.majorArr[i].id==this.user.majorId){
                this.user.majorName = this.majorArr[i].majorName;
              }
            }

            for (let i = 0; i < this.classArr.length; i++) {
              if(this.classArr[i].id==this.user.classId){
                this.user.className = this.classArr[i].className;
              }
            }
            let formData = this.qs.stringify(this.user);
            formData +="&code="+this.verification;
            let url = "http://localhost:9281/reg";
            this.axios.post(url,formData).then((response) =>{
              console.log("11111")
              console.log(response.data.stats);
              if(response.data.state==20000){
                this.$message({
                  showClose: true,
                  message: '注册成功',
                  type: 'success'
                });
                this.$router.push("/");
              }else{
                alert(response.data.message);
              }
            })
        }else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    getMajorArr(){
      let url = "http://localhost:9281/major/list";
      console.log(url);
      this.axios.get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.majorArr = jsonResult.data;
        }else{
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
          });
        }
      })


    },
    getClassArr(){
      this.user.classId = '';
      this.user.className='';
      console.log(this.user)
      let url = "http://localhost:9281/class/list?id="+this.user.majorId;
      console.log(url);
      this.axios.get(url).then((response)=>{
        let jsonResult = response.data;
        if(jsonResult.state==20000){
          this.classArr = jsonResult.data;
        }else{
          this.$alert(response.data.message, '错误', {
            confirmButtonText: '确定',
          });
        }
      })
    }
  },
  mounted() {
    //this.code(this.option);
    this.getMajorArr();
  }
}
</script>
